﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;

namespace MotionControl.Modules.LightSource.LightControl
{
    public class RS232Library
    {
        public SerialPort sPort;
        public RS232Library( string portName)
        {
            sPort = new SerialPort
            {
                BaudRate = 9600,
                StopBits = StopBits.One,
                DataBits = 8,
                Parity = Parity.None,
                PortName = portName
            };
        }

        public bool OpenPort()
        {
            try
            {
                sPort.Open();
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        public void ClosePort()
        {
            if (sPort.IsOpen)
            {
                sPort.Close();
            }
        }

        //public string createStr(byte command, byte channle, byte data)
        //{
        //    char* conHex = new char[3];

        //    string returnStr = "$"; //将第1通道亮度设为50，则以ASCII码向下写“$3103217”
        //    returnStr += command;
        //    returnStr += channle;
        //    if (data > 15)
        //    {
        //        sprintf(conHex, "0%X", data);
        //    }
        //    else
        //    {
        //        sprintf(conHex, "00%X", data);
        //    }
        //    returnStr = returnStr + conHex;
        //    //把所有的字符异或运算
        //    int i;
        //    BYTE xorData = returnStr[0];
        //    for (i = 1; i < returnStr.GetLength(); i++)
        //    {
        //        xorData = xorData ^ returnStr[i];
        //    }
        //    sprintf(conHex, "%X", xorData);
        //    returnStr = returnStr + conHex;
        //    return returnStr;
        //}

        private string GetCommandFormat(string cmd)
        {
            //特征字：$    1字节
            //命令字:1~4   1字节
            //通道字:1~4   1字节
            //数据：0+ff，ff表示0~255的16进制数   3字节
            //异或和校验字：特征字+命令字+通道字+数据的异或校验和  2字节  计算校验和时进行转换位ascii码后再进行计算
            string verify = "";
            if (cmd.Length == 6)
            {
                int temp = 0;
                Byte[] asciiData = System.Text.Encoding.ASCII.GetBytes(cmd);
                temp = asciiData[0];
                for (int i = 1; i < asciiData.Length; i++)
                {
                    temp = temp ^ asciiData[i];
                }
                verify = cmd + temp.ToString("X");
                return verify;
            }
            else
            {
                return verify;
            }
        }

        public string WriteCommand(string cmd)
        {
            string result = "&";
            string cmdResult = GetCommandFormat(cmd);
            try
            {
                if (cmdResult != "")
                {
                    if (sPort.IsOpen)
                    {
                        sPort.Write(cmdResult);
                        result = ReadData();
                        return result;
                    }
                    else
                    {
                        return result;
                    }
                }
                else
                {
                    return result;
                }
            }
            catch
            {
                return result;
            }
        }

        public string ReadData()
        {
            string result = "&";
            Byte[] buffer = new byte[25];          
            try
            {
                if (sPort.IsOpen)
                {
                    sPort.ReadTimeout = 500;
                    sPort.Read(buffer, 0, buffer.Count());
                    result = System.Text.Encoding.ASCII.GetString(buffer).Trim();
                }
                return result;
            }
            catch
            {
                return result;
            }
        }
    }
}
